package com.ahuan.controller;

import com.ahuan.domain.Role;
import com.ahuan.exception.BusinessException;
import com.ahuan.resp.Res;
import com.ahuan.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api/Role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @DeleteMapping("/delete")
    public Res deleteDept(@RequestParam("ids") String roleId){
        try {
            log.info("ResetPwd RoleId:{}", roleId);
            if(roleService.delete(roleId)){
                return Res.successOperate();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("角色删除失败");
        }

        return  Res.failOperate();
    }


    @PostMapping("/save")
    public Res saveDept(Role role) {
        try {
            role.setEditUser(MDC.get("userId"));
            log.info("role:{}", role);
            if (role.getRoleId() == null || role.getRoleId() == "") {
                if (roleService.addRole(role)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            } else {
                System.out.println("------------");
                if (roleService.editRole(role)) {
                    return Res.successOperate();
                } else {
                    return Res.failOperate();
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new BusinessException("角色保存失败");
        }
//        return Res.successOperate();
    }

    @PostMapping("/list")
    public Res getRoleList() {
        try {
            List<Role> list =  roleService.queryRoleList();
            log.info("查询到的角色列表为:{}",list);
            if(list != null && list.size() > 0){
                return Res.successOperate(list,list.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("角色列表查询失败");
        }
        return Res.failOperate();
    }



}
